#include "System.h"

//Statically allocate the incoming and outgoing Queues
BYTE SCI1_IncomingQueueStorage[RX_BUFFER_SIZE];
BYTE SCI1_OutgoingQueueStorage[TX_BUFFER_SIZE];

ByteQueue SCI1OutgoingQueue;
ByteQueue SCI1IncomingQueue;

void InitSCI1() 
{

  //Initialize the software Queues

InitByteQueue(&SCI1OutgoingQueue,TX_BUFFER_SIZE,SCI1_OutgoingQueueStorage);
InitByteQueue(&SCI1IncomingQueue,RX_BUFFER_SIZE,SCI1_IncomingQueueStorage);

   SCI1BD = (BUS_CLOCK/(16 * SCI_BAUD_RATE))+1;
   
   //No Parity, 8 databits, Normal Operation
   SCI1C1 = 0;
   
   SCI1C2_TE = 1;   //Enable Transmitter
   SCI1C2_RE = 1;   //Enable Reciever
   
   SCI1C2_RIE = 1;  //Enable Recieve Interrupts
                    //transmit interrupts will be enabled/
                    //Disabled by our queuing functions
                    
}



//Transmit Interrupt
interrupt VectorNumber_Vsci1tx void SCI1_Tx_IRQ(void)
{
  if(SCI1S1_TDRE)
  	{	
  	 if(BytesInQueue(&SCI1OutgoingQueue))
  		{
  			(void)ByteDequeue(&SCI1OutgoingQueue,(unsigned char *)(&SCI1D));
  		 }
  	 else
  	    {
  	      	//if we are done, turn off the interrupts
  	      	DISABLE_TX_IRQ;
  	    }
  	}

}

//Recieve Interrupt
interrupt VectorNumber_Vsci1rx void SCI1_Rx_IRQ(void)
{

  if(SCI1S1_RDRF ==1 )
  {
    (void)ByteEnqueue(&SCI1IncomingQueue,SCI1D);
 
  } 
}

